package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.config.properties.MinioProperties;
import com.atguigu.gmall.product.service.FileuploadService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.UploadObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

/**
 * @author lfy
 * @Description
 * @create 2023-08-15 14:38
 */
@Service
public class FileuploadServiceImpl implements FileuploadService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioProperties minioProperties;
    @Override
    public String upload(MultipartFile file) throws Exception {


        String formatDate = DateUtil.formatDate(new Date(), "yyyy/MM/dd");
        //对象存储中用的名字； 用当前日期作为文件夹名;  1）、文件夹归档  2）、文件名防重复
        String filename = formatDate+ "/" +UUID.randomUUID().toString() +"_"+ file.getOriginalFilename();
        String path = minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+filename;

        //TODO 把file数据存到Minio服务器


        //1、创建 MinioClient
        //2、准备 bucket

        //3、文件上传参数构造
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(filename) //对象存储中用的名字
                .stream(file.getInputStream(), file.getSize(), -1L)
                .contentType(file.getContentType())
                .build();

        //4、上传
        minioClient.putObject(putObjectArgs);


        // http://192.168.200.100:9000/gmall/AKFox_ZH-CN8586782340_1920x1080.jpg

        return path;
    }
}
